import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.StringTokenizer;

public class MyTelnetServer {

    ServerSocket serverSocket = null;

    public MyTelnetServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void run() throws IOException {
        System.out.println("启动服务器");
        Socket socket = serverSocket.accept();
        System.out.printf("[%s,%d] 客户端上线！\n",socket.getInetAddress(),socket.getPort());
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            while(true) {
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()) {
                    System.out.printf("[%s,%d] 客户端下线！\n",socket.getInetAddress(),socket.getPort());
                    break;
                }
                System.out.println("Waiting for UserName And Password");
                String LoginName = scanner.next();
                String Password = scanner.next();
                BufferedReader brFin = new BufferedReader(new FileReader("Passwords.txt"));
                String LoginInfo = brFin.readLine();
                boolean allow = false;
                PrintWriter printWriter = new PrintWriter(outputStream);
                while (LoginInfo != null) {
                    StringTokenizer st = new StringTokenizer(LoginInfo);
                    if (LoginName.equals(st.nextToken()) && Password.equals(st.nextToken())) {
                        System.out.println(1);
                        printWriter.println("TRUE");
                        printWriter.flush();
                        allow = true;
                        break;
                    }
                }
                brFin.close();
                if(!allow) {
                    printWriter.println("FALSE");
                    printWriter.flush();
                }
                while(allow) {
                    String request = scanner.next();
                    System.out.printf("[%s,%d]客户端\n",socket.getInetAddress(),socket.getPort());
                    System.out.println(request);
                    printWriter.println(request);
                    printWriter.flush();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        MyTelnetServer myTelnetServer = new MyTelnetServer(9090);
        myTelnetServer.run();
    }
}
